<?php
require_once('model.php');
define('DEBUG', false);

function get_json($array) {
	$output = "[";
	$length = sizeof($array);
	$i = 0;
	foreach ($array as $row) {
		$output .= "{";
		$inner = 0;
		$row_size = sizeof($row);
		foreach ($row as $key => $val) {
			$output .= '"' . $key . '"' . ':' .
			'"' . $val . '"';
			if (++$inner < $row_size)
			   $output .= ",";
		}
		$output .= "}";
		if (++$i < $length)
			$output .= ",";
	}
	$output .= "]";
	return $output;
}



if (!isset($_GET['all'])) {
  $left = $_GET['left'];
  $right = $_GET['right'];
  $bottom = $_GET['bottom'];
  $top = $_GET['top'];
  $all = 'false';
} else {
  $all = $_GET['all'];
}

$problem = new DiyModel("problems");



if ($all == "true")
  {
    $opt_params = array('conditions' => array('state !=' => -1),
			'order' => 'id desc',
		        'fields' => array('subject', 'state','id', 'lat', 'lng'));
  }
 else
   {
     $opt_params = array('conditions' =>
			 array('AND' =>
			       array('lat >' => $bottom,
				     'lat <' => $top,
				     'lng >' => $left,
				     'lng <' => $right,
				     'state !=' => -1)),
			 'fields' =>
			 array('subject', 'state', 'id', 'lat', 'lng'));
   }

$result = $problem->find('all', $opt_params);

foreach($result as &$item) {
  $file_name = '../photos/' . $item['id'] . '_thumb';
  if (file_exists($file_name))
    $item['img'] = 'photos/' . $item['id'] . '_thumb';
  else
    $item['img'] = 'photos/' . 'dummy_thumb';
  $size = getimagesize('../' . $item['img']);
  $item['width'] = $size[0];
  $item['height'] = $size[1];
}

echo get_json($result);

?>
